<template>
  <div :class="{'show':show}" class="header-search">
    <el-select
      ref="headerSearchSelect"
      v-model="search"
      :remote-method="querySearch2"
      filterable
      default-first-option
      remote
      placeholder="输入服务名称检索"
      class="header-search-select"
      @change="change"
    >
      <el-option v-for="item in options" :key="item.projectId" :value="item" :label="item.projectName" />
    </el-select>
  </div>
</template>

<script>
import { initData } from '@/api/data'

export default {
  name: 'HeaderSearch',
  data() {
    return {
      search: '',
      options: [],
      show: true
    }
  },
  computed: {
  },
  watch: {
    show(value) {
      if (value) {
        document.body.addEventListener('click', this.close)
      } else {
        document.body.removeEventListener('click', this.close)
      }
    }
  },
  mounted() {
  },
  methods: {
    click() {
      this.show = !this.show
      if (this.show) {
        this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus()
      }
    },
    close() {
      this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.blur()
      this.options = []
      this.show = false
    },
    change(val) {
      const { name } = this.$route
      if (name === 'DpServerDetail') {
        this.$router.push(`/`)
        this.$nextTick(() => {
          this.$router.push(`/deploy/dpserverdetail?projectId=${val.projectId}`)
        })
      } else {
        this.$router.push(`/deploy/dpserverdetail?projectId=${val.projectId}`)
      }
      this.search = ''
      this.options = []
    },
    querySearch(query) {
      initData('/api/dpUserServer', {
        page: 0,
        size: 10,
        name: query
      }).then(data => {
        this.options = data.content
      }).catch(err => {
        this.$notify({
          title: '获取项目详情失败' + err,
          type: 'error',
          duration: 2500
        })
      })
    },
    // 获取最近部署的项目
    querySearch2() {
      initData('/api/userHotProject/findByUserId', {}).then(data => {
        this.options = data
      }).catch(err => {
        this.$notify({
          title: '获取最近部署项目详情' + err,
          type: 'error',
          duration: 2500
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;

  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

   ::v-deep .el-input__inner {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }

  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
